const puppeteer = require('puppeteer');
let index = 0;
let urlindex = 1;
let targetUrl = `http://jandan.net/ooxx/page-${urlindex}#comments\\`;

function sleep(delay) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            try {
                resolve(1)
            } catch (e) {
                reject(0)
            }
        }, delay)
    })
}

function downLoadImg(imgUrl, suffix) {
    let fs = require('fs');
    let http = require('http');
    http.get(imgUrl, function(res){
        let imgData = "";
        let contentLength = parseInt(res.headers['content-length']);
        res.setEncoding("binary");
        res.on("data", function(chunk){
            imgData += chunk;
            let process = ((imgData.length)/contentLength) * 100;
            let percent = parseInt(((process).toFixed(0)));
        });

        res.on("end", function(){
            fs.writeFile(`./images/${suffix}`, imgData, "binary", function(err){
                if(err){
                    console.log("下载失败");
                }else{
                    index++;
                    console.log(`第${index}张图片下载完成`);
                }


            });
        });
    });

}


async function fn(url){
    const browser = await puppeteer.launch({headless: false});
    const page = await browser.newPage();
    await page.goto(url,{
        waitUntil: 'networkidle2'                               // 页面加载完毕
    });
    const result = await page.evaluate(()=>{
        let data = [] ;
        let elements = document.querySelectorAll('.row .text');
        for(let i of elements){
            let imgPath = i.querySelector('img').src;
            data.push({imgPath});
        }
        return data
    });

    // 开始下载
    for(let i of result){
        let name = i.imgPath.toString().substring(i.imgPath.toString().lastIndexOf("/"));
        await downLoadImg(i.imgPath,name)
    }

    urlindex++;
    console.log(urlindex);
    sleep(1000);
    browser.close();

}


fn(targetUrl)

